package cn.funnymap.lgis.tools.vector.util;

import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKBReader;

import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * WKT字符串工具类
 *
 * @author jiao xn
 */
public class WKTUtil {
    private WKTUtil() {}

    /**
     * 将多个 WKT 字符串合并成一个 WKT 字符串
     *
     * @param wktList 多个 WKT 字符串
     * @return 合并后的 WKT 字符串
     */
    public static String asOne(List<String> wktList) {
        if (wktList.size() ==  1) {
            return wktList.get(0);
        }

        String wktType = extractWktType(wktList.get(0));
        assert wktType != null;

        List<String> wktContentList = new ArrayList<>();

        if (wktType.toUpperCase().startsWith("POINT")) {
            // 针对多点（而不是MultiPoint）单独处理
            for (String wkt : wktList) {
                wktContentList.add(String.format("(%s)", extractWktContent(wkt)));
            }

            return String.format("MULTIPOINT (%s)", String.join(", ", wktContentList));
        } else {
            // 获取多个WKT的内容，即第一组()之内的内容
            for (String wkt : wktList) {
                wktContentList.add(extractWktContent(wkt));
            }

            return String.format("%s (%s)", wktType, String.join(", ", wktContentList));
        }
    }
    private static String extractWktContent(String wkt) {
        String reg = "(?<=\\().*(?=\\))";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(wkt);

        if (matcher.find()) {
            return matcher.group();
        }

        return null;
    }
    @SuppressWarnings("all")
    private static String extractWktType(String wkt) {
        String reg = ".*?(?=\\()";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(wkt);

        if (matcher.find()) {
            return matcher.group();
        }

        return null;
    }

    public static String mergeWkb2Wkt(List<String> wkbGeometries) throws ParseException {
        GeometryFactory geometryFactory = new GeometryFactory();
        WKBReader wkbReader = new WKBReader(geometryFactory);
        List<Polygon> polygons = new ArrayList<>();

        // 解析每个 WKB 字符串为 Polygon
        for (String wkb : wkbGeometries) {
            byte[] wkbBytes = Base64.getDecoder().decode(wkb);
            Geometry geometry = wkbReader.read(wkbBytes);
            if (geometry instanceof Polygon) {
                polygons.add((Polygon) geometry);
            }
        }

        // 合并 Polygon 列表为一个 MultiPolygon
        MultiPolygon multiPolygon = geometryFactory.createMultiPolygon(polygons.toArray(new Polygon[0]));

        // 返回 WKT 字符串
        return multiPolygon.toText();
    }
}
